package com.enzoism.springboot.dive.mock;

import com.enzoism.springboot.dive.common.RedisLockCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Random;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_SINGLETON;

/**
 * 模拟数据库进行数据交易(单例类)
 */
@Component()
@Scope(scopeName = SCOPE_SINGLETON)
public class MockDataSource {

    @Autowired()
    @Qualifier(value = "redisLock")
    private RedisLockCommon redisLock;

    private Integer coutNum;

    public Integer getCoutNum() {
        return coutNum;
    }

    public void setCoutNum(Integer coutNum) {
        String key = "dec_store_lock_countNum";
        long time = System.currentTimeMillis();
        try {
            //如果加锁失败
            Boolean success = redisLock.tryLock(key, String.valueOf(time));
            if (success) {
                System.out.println("------【" + Thread.currentThread().getName() + " 】锁获取成功");
                this.coutNum = coutNum;
                Thread.sleep(new Random().nextInt(1000));
                //解锁
                System.out.println("------锁释放成功");
                redisLock.unlock(key, String.valueOf(time));
            } else {
                System.out.println("------tryLock：没有获取锁");
            }
        } catch (Exception e) {
            System.out.println("------catch exception：没有获取锁");
            redisLock.unlock(key, String.valueOf(time));
        } finally {
        }
    }
}
